package factory;

import model.FarmMachine;
import model.Harvester;
import model.Seeder;
import model.Tractor;
import state.FarmMachineContext;
import state.WorkingState;

import java.util.ArrayList;
import java.util.List;

/**
 * 农场系统管理器
 * 使用工厂模式创建和管理农机设备
 */
public class FarmSystemManager {
    private List<FarmMachine> equipmentList = new ArrayList<>();

    public FarmMachine createEquipment(String type, String name) {
        FarmEquipmentFactory factory;

        switch (type.toUpperCase()) {
            case "TRACTOR":
                factory = new TractorFactory();
                break;
            case "HARVESTER":
                factory = new HarvesterFactory();
                break;
            case "SEEDER":
                factory = new SeederFactory();
                break;
            default:
                throw new IllegalArgumentException("未知的设备类型: " + type);
        }

        FarmMachine machine = factory.createEquipment(name);
        equipmentList.add(machine);
        return machine;
    }

    public void addEquipment(FarmMachine machine) {
        equipmentList.add(machine);
    }

    public List<FarmMachine> getEquipmentList() {
        return new ArrayList<>(equipmentList);
    }

    public FarmMachine getEquipmentById(String id) {
        for (FarmMachine machine : equipmentList) {
            if (machine.getDeviceId().equals(id)) {
                return machine;
            }
        }
        return null;
    }

    public void assignTask(String equipmentId, Task task) {
        FarmMachine machine = getEquipmentById(equipmentId);
        if (machine != null) {
            System.out.println("分配任务 [" + task.getName() + "] 给设备: " + machine.getName());
            // 触发状态转换
            FarmMachineContext context = machine.getStateContext();
            context.request();
            // 更新运行状态标记
            if (context.getState() instanceof WorkingState) {
                if (machine instanceof Tractor) {
                    ((Tractor) machine).setRunning(true);
                } else if (machine instanceof Harvester) {
                    ((Harvester) machine).setRunning(true);
                } else if (machine instanceof Seeder) {
                    ((Seeder) machine).setRunning(true);
                }
            }
        } else {
            System.out.println("未找到设备ID: " + equipmentId);
        }
    }
    public String getEquipmentStatusList() {
        StringBuilder statusList = new StringBuilder("===== 设备列表 =====\n");
        for (FarmMachine machine : equipmentList) {
            statusList.append("ID: ").append(machine.getDeviceId())
                    .append(" | 类型: ").append(machine.getType())
                    .append(" | 状态: ").append(machine.getStatusDescription())
                    .append("\n");
        }
        return statusList.toString();
    }
}